package com.work.customer.controller;

import com.github.pagehelper.Page;
import com.work.customer.pojo.Customer;
import com.work.customer.service.CustomerService;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    //添加农场组织
    @PostMapping("/add")
    public Result add(@RequestBody Customer customer){
        try {
            customerService.add(customer);
            return new Result(true, StatusCode.ADD_OK,"添加成功");
        }catch (Exception e){
            return new Result(false, StatusCode.ADD_ERROR,"添加失败");
        }

    }

    //修改农场组织信息
    @PostMapping("/update")
    public Result update(@RequestBody Customer customer){
        try {
            customerService.update(customer);
            return new Result(true, StatusCode.UPDATE_Ok,"更新成功");
        }catch (Exception e){
            return new Result(true, StatusCode.UPDATE_ERROR,"更新失败");
        }

    }

    //多条件查询+分页查询
    @GetMapping(value = "/find")
    public Result findPage(@RequestParam(required = false) Map searchMap,
                           @RequestParam(name = "page",defaultValue = "1",required = false) int page,
                           @RequestParam(name = "size",defaultValue = "5",required = false) int size
                          ){
        try {
            Page findPage = customerService.findPage(searchMap, page, size);
            return new Result(true, StatusCode.FIND_Ok,"查询成功",findPage);
        }catch (Exception e){
            return new Result(true, StatusCode.FIND_ERROR,"查询失败");
        }

    }

    //根据id查询
    @GetMapping(value = "/findById")
    public Result findById(@RequestParam("id") Integer id){
        try {
            Customer customer = customerService.findById(id);
            if(customer!=null){
                return new Result(true, StatusCode.FIND_Ok,"查询成功",customer);
            }else {
                return new Result(false,StatusCode.FIND_ERROR,"农场组织不存在");
            }

        }catch (Exception e){
            return new Result(true, StatusCode.FIND_ERROR,"查询失败");
        }

    }
}
